<?php

require_once 'Pipes/FileSystem/File/Finder.php';
require_once 'PipesImpl/Filter.php';

class Pipes_Filter implements PipesImpl_Filter
{
    private $_cursor = '';
    private $_conditions = array();
    private $_joinType = array();
    private $_substitutions = array();
    
    public function __get($key)
    {
        $this->_cursor = $key;
        return $this;
    }
    
    public function __call($method, $arguments)
    {
        $column = array_shift($arguments);
        $conditionType = false;
        switch ($method) {
            case 'and_' :
            case 'or_'  :
                $joinType = strtoupper(substr($method, 0, -1));
                $this->_joinType[] = $joinType;
                return $this;
                break;
            
            default :
                $conditionType = 'Pipes_Filter_Condition_' . ucfirst($method);
                $finder = new Pipes_FileSystem_File_Finder();
                $finder->findByClass($conditionType)->requireOnce();
                
                $this->_conditions[] = array(
                    'column' => $this->_cursor,
                    'condition' => new $conditionType()
                );
                
                $this->_substitutions[] = $column;
                break;
        }
                
        return $this;
    }
    
    public function getCondition()
    {
        $condition = '';
        reset($this->joinType);
        foreach ($this->_conditions as $cond) {
            $condition .= 
                "`{$cond['column']}` {$cond['condition']->toString()} ?";
            $joinType = current($this->_joinType);
            if ($joinType !== false) {
                $condition .= " $joinType ";
            }
            next($this->_joinType);
        }
        return $condition;
    }
    
    public function getSubstitutions()
    {
        return $this->_substitutions;
    }
}